﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Phone.Controls;
using Microsoft.Unsupported;
using Microsoft.Phone.Tasks;
using System.Windows.Media.Imaging;
using System.IO;
using Microsoft.Xna.Framework.Media;
using com.google.zxing;
using System.Windows.Data;


namespace iLikeWine
{
    public partial class insert_new_wine : PhoneApplicationPage
    {
        
        //private const string Con_String = @"isostore:/amit.sdf";
        private const string conn = @"isostore:/iLikeWine.sdf";
        // create a new city and add it to the context
        WineData wine = new WineData();

        // Declare the CameraCaptureTask object with page scope.
        CameraCaptureTask cameraCaptureTask;
        PhotoChooserTask photoChooserTask;
        BitmapImage bmp;
       
        // Constructor

        PickerBoxDialog dialog;
        PickerBoxDialogRegiao dialogRegiao;

        private string[] data = new string[] { "2012", "2011", "2010", "2009", "2008", "2007", "2006", "2005", "2004", "2003", "2002", "2001", "2000", "1999", "1998", "1997", "1996", "1995", "1994", "1993", "1992", "1991", "1990", "1989", "1988", "1987", "1986", "1985", "1984", "1983", "1982", "1981", "1980", "1979", "1978", "1977", "1976", "1975", "1974", "1973", "1972", "1971", "1970", "1969", "1968", "1967", "1966", "1965", "1964", "1963", "1962", "1961", "1960", "1959", "1958", "1957", "1956", "1955", "1954", "1953", "1952", "1951", "1950" };
        private string[] regiao = new string[] { "Douro", "Alentejo", "Dão", "Verde", "Bairrada", "Alvarinho", "Bordeux", "Alsace", "Burgundy", "Champagne", "Languedoc-Roussillon", "Loire", "Rhone", "Mosel", "Pfalz", "Emilia-Romagna", "Piedmont", "Puglia", "Sicily", "Tuscany", "Veneto", "Cigales", "Galicia", "Jumilia", "Montsant", "Navarra", "Penedes", "Priorat", "Ribera del Duero", "Rioja", "Toro", "Anderson Valley", "California", "North Carolina", "Oregon", "Mendoza", "Barossa", "Clare", "Coonawarra", "Granite Belt", "Colchagua", "Maipo", "Rapel valley" };

        private int selectedIndex;
        private int selectedIndexRegiao;


        PickerBoxDialog customDialog;
        PickerBoxDialogRegiao customDialogRegiao;

        BitmapImage tintoImage = new BitmapImage(new Uri("/iLikeWine;component/Images/vinho_tinto.png", UriKind.Relative));
        BitmapImage brancoImage = new BitmapImage(new Uri("/iLikeWine;component/Images/vinho_branco.png", UriKind.Relative));
        BitmapImage roseImage = new BitmapImage(new Uri("/iLikeWine;component/Images/vinho_rose.png", UriKind.Relative));

        //Contrutor
        public insert_new_wine()
        {
            InitializeComponent();
            //TiltEffect.SetIsTiltEnabled(this, true);
            this.buttonAno.DataContext = data[0];

            

            InitPickerBoxDialog();
            InitCustomPickerDialog();

            InitPickerBoxDialogRegiao();
            InitCustomPickerDialogRegiao();

            //Inicia CameraCaptureTask and assign the Completed handler in the page constructor.
            cameraCaptureTask = new CameraCaptureTask();
            cameraCaptureTask.Completed += new EventHandler<PhotoResult>(photoCaptureOrSelectionCompleted);
            photoChooserTask = new PhotoChooserTask();
            photoChooserTask.Completed += new EventHandler<PhotoResult>(photoCaptureOrSelectionCompleted);

            textBox1.Text = "";

                      
        }

       
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            cameraCaptureTask.Show();
            //NavigationService.Navigate(new Uri("/Take_photo.xaml", UriKind.RelativeOrAbsolute));
        }

        private void InitCustomPickerDialog()
        {

            // Assing it to the page's DataContext

            this.customDialog = new PickerBoxDialog();
            this.customDialog.Title = "ACCENTS";

            // Assign our style to the dialog
            this.customDialog.Style = this.Resources["Custom"] as Style;


        }

        private void InitCustomPickerDialogRegiao()
        {

            this.customDialogRegiao = new PickerBoxDialogRegiao();
            this.customDialogRegiao.Title = "ACCENTS";

            // Assign our style to the dialog
            this.customDialogRegiao.Style = this.Resources["Custom2"] as Style;


        }


        private void InitPickerBoxDialog()
        {

            dialog = new PickerBoxDialog();
            // Assign data source and title
            dialog.ItemSource = data;

            dialog.Title = "Ano do Vinho";
            // Hook up into closed event
            dialog.Closed += new EventHandler(dialog_Closed);



        }

        private void InitPickerBoxDialogRegiao()
        {
            dialogRegiao = new PickerBoxDialogRegiao();
            // Assign data source and title
            dialogRegiao.ItemSource = regiao;

            dialogRegiao.Title = "Região Demarcada do Vinho";
            // Hook up into closed event
            dialogRegiao.Closed += new EventHandler(dialog_ClosedRegiao);

        }


        void dialog_Closed(object sender, EventArgs e)
        {

            selectedIndex = dialog.SelectedIndex;
            // Dialog closed. Assign the value to the button
            this.buttonAno.DataContext = data[selectedIndex];
        }

        void dialog_ClosedRegiao(object sender, EventArgs e)
        {

            selectedIndexRegiao = dialogRegiao.SelectedIndexRegiao;
            // Dialog closed. Assign the value to the button
            this.buttonRegiao.DataContext = regiao[selectedIndexRegiao];

        }

        private void buttonAno_Click(object sender, RoutedEventArgs e)
        {
            // Display dialog

            dialog.SelectedIndex = selectedIndex;
            dialog.Show();
        }

        private void buttonRegiao_Click(object sender, RoutedEventArgs e)
        {

            dialogRegiao.SelectedIndexRegiao = selectedIndexRegiao;
            dialogRegiao.Show();
        }

        private void button3_Click(object sender, RoutedEventArgs e)
        {
           NavigationService.RemoveBackEntry();
           NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute));
           
        }

        void photoCaptureOrSelectionCompleted(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {
                bmp = new BitmapImage();
                bmp.SetSource(e.ChosenPhoto);
                image1.Source = bmp;
                image1.Stretch = Stretch.Uniform;

                // swap UI element states
                //savePhotoButton.IsEnabled = true;
                MessageBox.Show("Vinho foi criado com sucesso");
            }
            else
            {
                //savePhotoButton.IsEnabled = false;
                MessageBox.Show("Task Result Error: " + e.TaskResult.ToString()); 
            }
        }

       private void button4_Click(object sender, RoutedEventArgs e)
        {
            iLike.ScanBarCode.BarCodeManager.StartScan(
                // on success
               (b) => Dispatcher.BeginInvoke(() =>
               {
                   tbScanResultQR.Text = b;
                   NavigationService.GoBack();
               }),
                // on error
               (ex) => Dispatcher.BeginInvoke(() =>
               {
                   tbScanResultQR.Text = ex.Message;
                   NavigationService.GoBack();
               }),
                // Please, decode a QR Code
               BarcodeFormat.QR_CODE);
        }

       private void AddWineData()
       {
           //-->
                      String t; BitmapImage imageTipo;
           if (Tinto.IsChecked == true) { t = Tinto.Name; imageTipo = tintoImage; }
           else if (Branco.IsChecked == true) { t = Branco.Name;  imageTipo = brancoImage;}
           else {t = Rose.Name; imageTipo = roseImage;}
            String rr;
            //if (buttonRegiao.DataContext == null) rr = "Não Defenido";
            //else rr = buttonRegiao.DataContext.ToString();


           using (var ctx = new iLikeWineDataContext(conn))
           {
               //montar o objecto Wine
               Wine w = new Wine()
               {
                   Nome = textBox1.Text,
                   QrCode = tbScanResultQR.Text,
                   Tipo = t,
                   Ranking = ranking.Text,
                   Www=textBox3.Text,
                   ImageSource = imageTipo,
                   //BarCode = textBox4.Text,
                  //Fotografia = image1.Source.GetVisualChild<BinaryBitmap>,
                  //   Fotografia = bmp,
                    Ano = buttonAno.DataContext.ToString(),
                   Regiao = buttonRegiao.DataContext.ToString(),//rr,
                   Comentario = textBox2.Text
                   
               };

               ctx.Wines.InsertOnSubmit(w);
               ctx.SubmitChanges();  
           }

        
        
          
       }


       private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
       {

       }

       private void button2_Click(object sender, RoutedEventArgs e)
       {
           try
           {
               this.AddWineData();
               MessageBox.Show("Vinho foi criado com sucesso");
               textBox1.Text = "";
               tbScanResultQR.Text = "";
               textBox3.Text = "";
               ranking.Text = "1";
               textBox2.Text = "";
           }
           catch (Exception) // catches without assigning to a variable
           {
               MessageBox.Show("Erro ao criar o vinho!");
           }
       }

       private void image1_ImageFailed(object sender, ExceptionRoutedEventArgs e)
       {

       }

       private void image2_ImageFailed(object sender, ExceptionRoutedEventArgs e)
       {
           this.AddWineData();
           MessageBox.Show("Vinho foi criado com sucesso");
           textBox1.Text = "";
       }

       private void image3_ImageFailed(object sender, ExceptionRoutedEventArgs e)
       {

       }

        
    }
}